<template>
  <div class="page-container">
    <el-card>
      <!-- 搜索栏 -->
      <el-form :model="queryParams" inline>
        <el-form-item label="用户ID：">
          <el-input
            v-model="queryParams.uid"
            placeholder="请输入用户ID"
            :maxLength="200"
            allowClear
            clearable
          />
        </el-form-item>
        <el-form-item label="日期范围：">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            @change="handleDateChange"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="handleAdd">新增体检记录</el-button>
      </div>

      <!-- 指标趋势提示 -->
      <el-alert
        v-if="indicatorData && indicatorData.list.length > 0"
        title="健康指标趋势"
        type="success"
        :closable="false"
        style="margin-bottom: 16px"
      >
        <template #default>
          共找到 <strong>{{ indicatorData.list.length }}</strong> 条体检记录，数据趋势可用于分析健康变化
        </template>
      </el-alert>

      <!-- 表格 -->
      <el-table :data="tableData" v-loading="loading" border stripe>
        <el-table-column prop="fsid" label="记录ID" width="180" />
        <el-table-column prop="userName" label="用户姓名" width="120" />
        <el-table-column prop="userPhone" label="手机号" width="130" />
        <el-table-column prop="checkupDate" label="体检日期" width="120" sortable />
        <el-table-column label="甘油三酯" width="110">
          <template #default="{ row }">
            <el-tag :type="getIndicatorType(parseFloat(row.triglyceride), 0, 1.7)">
              {{ row.triglyceride }} mmol/L
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="HDL胆固醇" width="120">
          <template #default="{ row }">
            <el-tag :type="getIndicatorType(parseFloat(row.HdlCholesterol), 1.0, 999, true)">
              {{ row.HdlCholesterol }} mmol/L
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="LDL胆固醇" width="120">
          <template #default="{ row }">
            <el-tag :type="getIndicatorType(parseFloat(row.LdlCholesterol), 0, 3.4)">
              {{ row.LdlCholesterol }} mmol/L
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bloodPressure" label="血压" width="120" />
        <el-table-column label="超敏C反应蛋白" width="130">
          <template #default="{ row }">
            <el-tag :type="getIndicatorType(parseFloat(row.hsCRP), 0, 3)">
              {{ row.hsCRP }} mg/L
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="肝功能(ALT)" width="120">
          <template #default="{ row }">
            <el-tag :type="getIndicatorType(parseFloat(row.alanineAminotransferase), 0, 40)">
              {{ row.alanineAminotransferase }} U/L
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleView(row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 暂无数据提示 -->
      <el-empty v-if="!loading && tableData.length === 0" description="暂无数据，请输入用户ID查询" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="140px"
        v-loading="formLoading"
      >
        <el-form-item label="用户ID：" prop="uid">
          <el-input
            v-model="formData.uid"
            placeholder="请输入用户ID"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="体检日期：" prop="checkupDate">
          <el-date-picker
            v-model="formData.checkupDate"
            type="date"
            placeholder="请选择体检日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="报告文件：" prop="reportFile">
          <el-input
            v-model="formData.reportFile"
            placeholder="请输入报告文件路径"
            :maxLength="200"
            allowClear
          />
        </el-form-item>
        <el-form-item label="甘油三酯：" prop="triglyceride">
          <el-input
            v-model="formData.triglyceride"
            placeholder="请输入甘油三酯值"
            :maxLength="200"
            allowClear
          >
            <template #append>mmol/L</template>
          </el-input>
        </el-form-item>
        <el-form-item label="HDL胆固醇：" prop="HdlCholesterol">
          <el-input
            v-model="formData.HdlCholesterol"
            placeholder="请输入HDL胆固醇值"
            :maxLength="200"
            allowClear
          >
            <template #append>mmol/L</template>
          </el-input>
        </el-form-item>
        <el-form-item label="LDL胆固醇：" prop="LdlCholesterol">
          <el-input
            v-model="formData.LdlCholesterol"
            placeholder="请输入LDL胆固醇值"
            :maxLength="200"
            allowClear
          >
            <template #append>mmol/L</template>
          </el-input>
        </el-form-item>
        <el-form-item label="血压：" prop="bloodPressure">
          <el-input
            v-model="formData.bloodPressure"
            placeholder="请输入血压（如：120/80）"
            :maxLength="200"
            allowClear
          >
            <template #append>mmHg</template>
          </el-input>
        </el-form-item>
        <el-form-item label="超敏C反应蛋白：" prop="hsCRP">
          <el-input
            v-model="formData.hsCRP"
            placeholder="请输入超敏C反应蛋白值"
            :maxLength="200"
            allowClear
          >
            <template #append>mg/L</template>
          </el-input>
        </el-form-item>
        <el-form-item label="肝功能(ALT)：" prop="alanineAminotransferase">
          <el-input
            v-model="formData.alanineAminotransferase"
            placeholder="请输入肝功能ALT值"
            :maxLength="200"
            allowClear
          >
            <template #append>U/L</template>
          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="formLoading" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="指标详情" width="700px">
      <el-descriptions :column="2" border v-if="currentDetail">
        <el-descriptions-item label="记录ID">{{ currentDetail.fsid }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentDetail.uid }}</el-descriptions-item>
        <el-descriptions-item label="用户姓名">{{ currentDetail.userName }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ currentDetail.userPhone }}</el-descriptions-item>
        <el-descriptions-item label="体检日期">{{ currentDetail.checkupDate }}</el-descriptions-item>
        <el-descriptions-item label="报告文件" :span="2">
          {{ currentDetail.reportFile }}
        </el-descriptions-item>
        <el-descriptions-item label="甘油三酯">
          {{ currentDetail.triglyceride }} mmol/L
          <el-tag :type="getIndicatorType(parseFloat(currentDetail.triglyceride), 0, 1.7)" size="small" style="margin-left: 8px">
            {{ getIndicatorStatus(parseFloat(currentDetail.triglyceride), 0, 1.7) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="HDL胆固醇">
          {{ currentDetail.HdlCholesterol }} mmol/L
          <el-tag :type="getIndicatorType(parseFloat(currentDetail.HdlCholesterol), 1.0, 999, true)" size="small" style="margin-left: 8px">
            {{ getIndicatorStatus(parseFloat(currentDetail.HdlCholesterol), 1.0, 999, true) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="LDL胆固醇">
          {{ currentDetail.LdlCholesterol }} mmol/L
          <el-tag :type="getIndicatorType(parseFloat(currentDetail.LdlCholesterol), 0, 3.4)" size="small" style="margin-left: 8px">
            {{ getIndicatorStatus(parseFloat(currentDetail.LdlCholesterol), 0, 3.4) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="血压">
          {{ currentDetail.bloodPressure }} mmHg
        </el-descriptions-item>
        <el-descriptions-item label="超敏C反应蛋白">
          {{ currentDetail.hsCRP }} mg/L
          <el-tag :type="getIndicatorType(parseFloat(currentDetail.hsCRP), 0, 3)" size="small" style="margin-left: 8px">
            {{ getIndicatorStatus(parseFloat(currentDetail.hsCRP), 0, 3) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="肝功能(ALT)">
          {{ currentDetail.alanineAminotransferase }} U/L
          <el-tag :type="getIndicatorType(parseFloat(currentDetail.alanineAminotransferase), 0, 40)" size="small" style="margin-left: 8px">
            {{ getIndicatorStatus(parseFloat(currentDetail.alanineAminotransferase), 0, 40) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ currentDetail.createTime }}
        </el-descriptions-item>
        <el-descriptions-item label="更新时间">
          {{ currentDetail.updateTime }}
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getIndicatorList,
  getReportDetail,
  createReport,
  updateReport,
  deleteReport
} from '@/api/modules/health'
import type { HealthReport, SaveReportParams, IndicatorData } from '@/api/types'

// 查询参数
const queryParams = reactive({
  uid: '',
  startDate: undefined as string | undefined,
  endDate: undefined as string | undefined
})

// 日期范围
const dateRange = ref<string[]>([])

// 处理日期范围变化
const handleDateChange = (dates: string[] | null) => {
  if (dates && dates.length === 2) {
    queryParams.startDate = dates[0]
    queryParams.endDate = dates[1]
  } else {
    queryParams.startDate = undefined
    queryParams.endDate = undefined
  }
}

// 数据相关
const loading = ref(false)
const tableData = ref<HealthReport[]>([])
const indicatorData = ref<IndicatorData | null>(null)

// 查询数据
const handleQuery = async () => {
  if (!queryParams.uid) {
    ElMessage.warning('请输入用户ID')
    return
  }

  try {
    loading.value = true
    const { data } = await getIndicatorList(queryParams)
    indicatorData.value = data
    tableData.value = data.list
  } catch (error) {
    console.error('getIndicatorList error:', error)
    tableData.value = []
  } finally {
    loading.value = false
  }
}

// 重置
const handleReset = () => {
  queryParams.uid = ''
  queryParams.startDate = undefined
  queryParams.endDate = undefined
  dateRange.value = []
  tableData.value = []
  indicatorData.value = null
}

// 表单相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref<FormInstance>()
const formLoading = ref(false)
const currentEditId = ref<string>('')

const formData = reactive<SaveReportParams>({
  uid: '',
  reportFile: '',
  triglyceride: '',
  HdlCholesterol: '',
  LdlCholesterol: '',
  bloodPressure: '',
  hsCRP: '',
  alanineAminotransferase: '',
  checkupDate: ''
})

const formRules: FormRules = {
  uid: [{ required: true, message: '请输入用户ID', trigger: 'blur' }],
  checkupDate: [{ required: true, message: '请选择体检日期', trigger: 'change' }],
  reportFile: [{ required: true, message: '请输入报告文件路径', trigger: 'blur' }],
  triglyceride: [{ required: true, message: '请输入甘油三酯值', trigger: 'blur' }],
  HdlCholesterol: [{ required: true, message: '请输入HDL胆固醇值', trigger: 'blur' }],
  LdlCholesterol: [{ required: true, message: '请输入LDL胆固醇值', trigger: 'blur' }],
  bloodPressure: [{ required: true, message: '请输入血压', trigger: 'blur' }],
  hsCRP: [{ required: true, message: '请输入超敏C反应蛋白值', trigger: 'blur' }],
  alanineAminotransferase: [{ required: true, message: '请输入肝功能ALT值', trigger: 'blur' }]
}

// 详情相关
const detailVisible = ref(false)
const currentDetail = ref<HealthReport | null>(null)

// 新增
const handleAdd = () => {
  dialogTitle.value = '新增体检记录'
  currentEditId.value = ''
  resetFormData()
  // 如果已经输入了用户ID，自动填充
  if (queryParams.uid) {
    formData.uid = queryParams.uid
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = async (row: HealthReport) => {
  dialogTitle.value = '编辑体检记录'
  currentEditId.value = row.fsid
  try {
    formLoading.value = true
    const { data } = await getReportDetail(row.fsid)
    Object.assign(formData, {
      uid: data.uid,
      reportFile: data.reportFile,
      triglyceride: data.triglyceride,
      HdlCholesterol: data.HdlCholesterol,
      LdlCholesterol: data.LdlCholesterol,
      bloodPressure: data.bloodPressure,
      hsCRP: data.hsCRP,
      alanineAminotransferase: data.alanineAminotransferase,
      checkupDate: data.checkupDate
    })
    dialogVisible.value = true
  } catch (error) {
    console.error('getReportDetail error:', error)
  } finally {
    formLoading.value = false
  }
}

// 查看
const handleView = async (row: HealthReport) => {
  try {
    const { data } = await getReportDetail(row.fsid)
    currentDetail.value = data
    detailVisible.value = true
  } catch (error) {
    console.error('getReportDetail error:', error)
  }
}

// 删除
const handleDelete = (row: HealthReport) => {
  ElMessageBox.confirm('确定要删除该体检记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        await deleteReport(row.fsid)
        ElMessage.success('删除成功')
        // 重新查询
        handleQuery()
      } catch (error) {
        console.error('deleteReport error:', error)
      }
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    formLoading.value = true

    if (currentEditId.value) {
      // 编辑
      await updateReport(currentEditId.value, formData)
      ElMessage.success('编辑成功')
    } else {
      // 新增
      await createReport(formData)
      ElMessage.success('新增成功')
    }

    dialogVisible.value = false
    // 重新查询
    handleQuery()
  } catch (error) {
    console.error('handleSubmit error:', error)
  } finally {
    formLoading.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetFormData()
}

// 重置表单数据
const resetFormData = () => {
  Object.assign(formData, {
    uid: '',
    reportFile: '',
    triglyceride: '',
    HdlCholesterol: '',
    LdlCholesterol: '',
    bloodPressure: '',
    hsCRP: '',
    alanineAminotransferase: '',
    checkupDate: ''
  })
}

// 获取指标状态类型（用于标签颜色）
const getIndicatorType = (value: number, min: number, max: number, reverse: boolean = false): 'success' | 'warning' | 'danger' | 'info' => {
  if (isNaN(value)) return 'info'

  if (reverse) {
    // HDL胆固醇，值越高越好
    return value >= min ? 'success' : 'danger'
  } else {
    // 其他指标，值在范围内为正常
    if (value >= min && value <= max) {
      return 'success'
    } else if (value > max) {
      return 'danger'
    } else {
      return 'warning'
    }
  }
}

// 获取指标状态文本
const getIndicatorStatus = (value: number, min: number, max: number, reverse: boolean = false) => {
  if (isNaN(value)) return '未知'

  if (reverse) {
    return value >= min ? '正常' : '偏低'
  } else {
    if (value >= min && value <= max) {
      return '正常'
    } else if (value > max) {
      return '偏高'
    } else {
      return '偏低'
    }
  }
}
</script>

<style scoped lang="scss">
.page-container {
  .toolbar {
    margin-bottom: 16px;
  }
}
</style>
